#!/usr/bin/env python3
"""
Windows平台打包模块
提供Windows平台专用的应用程序打包功能
"""

import os
import subprocess
import shutil
import tempfile
from pathlib import Path
import tomli

# 项目根目录
PROJECT_ROOT = Path(__file__).parent.parent
RESOURCES_DIR = PROJECT_ROOT / "resources"
BUILD_DIR = PROJECT_ROOT / "build"
DIST_DIR = PROJECT_ROOT / "dist"

def build_windows_package(name, main_script, config):
    """
    Windows平台打包
    
    参数:
        name (str): 应用程序名称
        main_script (str): 主脚本文件名
        config (object): 打包配置对象，包含以下属性：
            - one_file (bool): 是否使用单文件模式
            - windowed (bool): 是否使用窗口模式
            - build_type (str): 打包类型 ('app' 或 'installer')
    
    返回:
        bool: 打包是否成功
    """
    print("正在打包Windows应用程序...")
    
    cmd = [
        "pyinstaller",
        "--name", name,
        "--distpath", str(DIST_DIR),
        "--workpath", str(BUILD_DIR),
        "--specpath", str(BUILD_DIR),
    ]
    
    if config.one_file:
        cmd.append("--onefile")
    
    if config.windowed:
        cmd.append("--windowed")
    
    # 添加图标
    icon_path = RESOURCES_DIR / "icons" / "app-icon.ico"
    if icon_path.exists():
        cmd.extend(["--icon", str(icon_path)])
    
    # 添加数据文件
    cmd.extend(["--add-data", f"{RESOURCES_DIR}{os.pathsep}resources"])
    
    # PySide6相关配置
    cmd.extend([
        "--hidden-import", "PySide6.QtCore",
        "--hidden-import", "PySide6.QtGui", 
        "--hidden-import", "PySide6.QtWidgets",
        "--collect-all", "PySide6",
        "--collect-all", "shiboken6"
    ])
    
    cmd.append(str(PROJECT_ROOT / main_script))
    
    try:
        subprocess.run(cmd, check=True)
        print("Windows应用程序打包完成!")
        
        if config.build_type == "installer":
            return _create_windows_installer(name)
        
        print(f"输出目录: {DIST_DIR}")
        return True
        
    except subprocess.CalledProcessError as e:
        print(f"打包失败: {e}")
        return False

def _create_windows_installer(name):
    """创建Windows安装程序（EXE格式）"""
    print("创建Windows NSIS安装程序...")
    
    # 检查NSIS是否安装
    try:
        subprocess.run(["makensis", "/VERSION"], check=True, capture_output=True)
    except (subprocess.CalledProcessError, FileNotFoundError):
        print("警告: NSIS未安装，跳过安装程序创建")
        print("请安装NSIS: https://nsis.sourceforge.io/Download")
        return True
    
    # 从pyproject.toml读取版本信息
    pyproject_path = PROJECT_ROOT / "pyproject.toml"
    with open(pyproject_path, 'rb') as f:
        pyproject_data = tomli.load(f)
    version = pyproject_data.get('project', {}).get('version', '1.0.0')
    
    # 使用现有的NSIS脚本文件
    template_path = PROJECT_ROOT / "scripts" / "windows_installer.nsi"
    script_path = BUILD_DIR / f"{name}_installer.nsi"
    
    try:
        # 读取模板并替换变量
        with open(template_path, 'r', encoding='utf-8') as f:
            template = f.read()
        
        app_name = name.replace('-', ' ').title()
        nsis_script = template.replace('{{APP_NAME}}', app_name)
        nsis_script = nsis_script.replace('{{APP_VERSION}}', version)
        nsis_script = nsis_script.replace('{{EXE_NAME}}', name)
        
        # 写入处理后的脚本
        with open(script_path, 'w', encoding='utf-8') as f:
            f.write(nsis_script)
        
        # 运行NSIS编译
        subprocess.run(["makensis", str(script_path)], check=True)
        
        installer_path = DIST_DIR / f"{name}_installer.exe"
        if installer_path.exists():
            print(f"Windows安装程序创建完成: {installer_path}")
            return True
        else:
            print("安装程序创建失败")
            return False
            
    except Exception as e:
        print(f"创建安装程序失败: {e}")
        return False